package com.ucap.weking.guangan.Activitys;

import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.ucap.weking.guangan.R;
import com.ucap.weking.guangan.base.BaseFragment;
import com.ucap.weking.guangan.dialog.AboutDialog;
import com.ucap.weking.guangan.dialog.ShareDialog;
import com.ucap.weking.guangan.fragments.HomeContent1;
import com.ucap.weking.guangan.fragments.HomeContent2;
import com.ucap.weking.guangan.fragments.HomeContent3;
import com.ucap.weking.guangan.fragments.HomeContent4;
import com.ucap.weking.guangan.tools.NotificationUtils;
import com.ucap.weking.guangan.tools.PrefUtils;
import com.ucap.weking.guangan.tools.VersionTestingTools;
import com.ucap.weking.guangan.views.MyToast;
import com.ucap.weking.guangan.views.TabButton;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.List;

import butterknife.InjectView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;

public class HomeActivity extends AppCompatActivity {

    @InjectView(R.id.tab_button)
    TabButton tabButton;
    @InjectView(R.id.fl_content)
    FrameLayout flContent;
    @InjectView(R.id.iv_menu)
    ImageView ivMenu;
    @InjectView(R.id.dl_let_content)
    DrawerLayout dlLeftContent;
    @InjectView(R.id.nv_menu_item)
    NavigationView nvMenuItem;
    @InjectView(R.id.iv_push)
    ImageView ivPush;
    TextView tvMenuAppName;
    public static int CALL_PHONE_12345_PERMISSION = 12345;
    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.inject(this);
        VersionTestingTools.testingVersion(this, false);//版本检测
        NotificationUtils.permission(this);//通知检测是否开启
        intiView();
        intiData();
        setPushService();
    }

    private void setPushService() {
        ivPush.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pushMsg(v);
            }
        });


    }

    public void pushMsg(View view) {
        popupWindow = new PopupWindow(this);
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        View inflate = LayoutInflater.from(this).inflate(R.layout.popup_layout, null);
        Switch aSwitchPush = (Switch) inflate.findViewById(R.id.switch_push);
        popupWindow.setContentView(inflate);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.showAsDropDown(view);
        boolean pushStopped = JPushInterface.isPushStopped(getApplicationContext());//判读极光推送是否停止
        aSwitchPush.setChecked(!pushStopped);
        aSwitchPush.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (JPushInterface.isPushStopped(getApplicationContext())) {
                    MyToast.showTrue(HomeActivity.this, "推送已开启！");
                    JPushInterface.resumePush(HomeActivity.this);//恢复推送
                } else if (!JPushInterface.isPushStopped(getApplicationContext())) {
                    MyToast.showTrue(HomeActivity.this, "推送已关闭！");
                    JPushInterface.stopPush(HomeActivity.this);//停止推送
                }
            }
        });
    }

    public void intiView() {
        addFragment(new HomeContent1());
        tabButton.setOnChange(new TabButton.OnChange() {
            @Override
            public void change(int position) {
                switch (position) {
                    case 0:
                        addFragment(new HomeContent1());
                        break;
                    case 1:
                        addFragment(new HomeContent2());
                        break;
                    case 2:
                        addFragment(new HomeContent3());
                        break;
                    case 3:
                        addFragment(new HomeContent4());
                        break;
                }
            }
        });
        View headerView = nvMenuItem.getHeaderView(0);
        tvMenuAppName = (TextView) headerView.findViewById(R.id.tv_menu_app);
    }

    public void intiData() {
        ivMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlLeftContent.openDrawer(GravityCompat.START);
            }
        });

        dlLeftContent.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                try {
                    nvMenuItem.getMenu().getItem(0).setTitle("清理缓存        " + getTotalCacheSize(HomeActivity.this));
                } catch (Exception e) {
                    nvMenuItem.getMenu().getItem(0).setTitle("清理缓存");
                }
            }

            @Override
            public void onDrawerClosed(View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        nvMenuItem.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull final MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_cache://清理缓存
                        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeActivity.this);
                        dialog.setMessage("确定清除缓存!");
                        dialog.setTitle("提示");
                        dialog.setNegativeButton("取消", null);
                        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                try {
                                    clearAllCache(getApplicationContext());
                                    item.setTitle("清理缓存        0.0MB");
                                    Toast.makeText(getApplicationContext(), "清理成功!", Toast.LENGTH_SHORT).show();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        try {
                            long temp = getCacheSize();
                            if (temp > 0) {
                                dialog.show();
                            } else {
                                Toast.makeText(getApplicationContext(), "当前没有缓存清理!", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case R.id.menu_share://分享
                        ShareDialog.showDialog(HomeActivity.this);
                        break;
                    case R.id.menu_update:
                        VersionTestingTools.testingVersion(HomeActivity.this, true);
                        break;
                    case R.id.menu_about://关于
                        AboutDialog.showDialog(HomeActivity.this);
                        break;

                }
                return true;
            }
        });

        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            String appName = "中国广安" + "v" + packageInfo.versionName + "(" + packageInfo.versionCode + ")";
            tvMenuAppName.setText(appName);
        } catch (PackageManager.NameNotFoundException e) {
        }
    }

    public void addFragment(BaseFragment fragment) {
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction().replace(R.id.fl_content, fragment).commit();
    }

    /**
     * 获取缓存大小
     *
     * @param context
     * @return
     * @throws Exception
     */
    public String getTotalCacheSize(Context context) throws Exception {
        long cacheSize = getFolderSize(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += getFolderSize(context.getExternalCacheDir());
        }
        return getFormatSize(cacheSize);
    }

    /**
     * 计算缓存
     *
     * @param cacheSize
     * @return
     */
    private String getFormatSize(long cacheSize) {

        return (double) ((cacheSize / 1024) / 1024) + "MB";
    }

    /**
     * 根据目录查找缓存
     *
     * @param file
     * @return
     * @throws Exception
     */
    public long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 清除指定缓存
     *
     * @param dir
     * @return
     */
    private boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    /**
     * 清除缓存
     *
     * @param context
     */
    public void clearAllCache(Context context) {
        deleteDir(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteDir(context.getExternalCacheDir());
        }
    }

    /**
     * 获取清理后的缓存
     *
     * @return
     * @throws Exception
     */
    private long getCacheSize() throws Exception {
        long temp = getFolderSize(getApplicationContext().getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            temp += getFolderSize(getApplicationContext().getExternalCacheDir());
        }
        return temp;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 12345: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_CALL);
                    intent.setData(Uri.parse("tel:12345"));
                    startActivity(intent);
                } else {
                    MyToast.showTrue(HomeActivity.this, "权限申请失败，未能完成拨号！");
                }
                break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
